package service

import (
	"netdisk/dao"
	"netdisk/models"
	"time"
)

func NonUserToken(email, tokentype string) *models.UserToken {
	usertoken := &models.UserToken{Email: email, TokenType: tokentype}
	_, _ = dao.DB.Get(usertoken)
	if usertoken.IsActive == 1 {
		nowDate := time.Now()
		if nowDate.After(usertoken.ExpiresTime) {
			usertoken.IsActive = 0
			_, _ = dao.DB.Update(usertoken)
			return usertoken
		}
		panic("更新失败")
	}
	return &models.UserToken{Email: email, TokenType: tokentype}
}

func AddToken(userToken *models.UserToken, token string, expiresTime time.Time) {
	userToken.Token = token
	userToken.ExpiresTime = expiresTime
	userToken.IsActive = 1
	_, _ = dao.DB.InsertOne(userToken)
}

//使用token，验证token有效性，使之失效。无效token抛出异常
func UseUserToken(email, token, tokenType string) {
	userToken := HaveUserToken(email, token, tokenType)
	userToken.IsActive = 0
	dao.DB.Update(userToken)
}

//使用token，验证token有效性，使之失效。无效token抛出异常
func HaveUserToken(email, token, tokenType string) *models.UserToken {
	userToken := &models.UserToken{Email: email, Token: token, TokenType: tokenType}
	dao.DB.Get(userToken)
	date := time.Now()
	if userToken.IsActive == 0 || date.After(userToken.ExpiresTime) {
		panic("无效Token")
	}
	return userToken
}
